home *** CD-ROM | disk | FTP | other *** search
- Path: fc.hp.com!news
- From: Rick Wells <rwells>
- Newsgroups: comp.lang.c
- Subject: Re: changing strings via pointers
- Date: 22 Feb 1996 17:25:56 GMT
- Organization: Hewlett-Packard Fort Collins Site
- Message-ID: <4gi8v4$alk@fcnews.fc.hp.com>
- References: <1996Feb22.125436.25503@leeds.ac.uk>
- NNTP-Posting-Host: blkbear.fc.hp.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.1N (X11; I; HP-UX A.09.07 9000/715)
- X-URL: news:1996Feb22.125436.25503@leeds.ac.uk
-
- csyamc@scs.leeds.ac.uk (A M Casey) wrote:
- >I reading in strings from a file using fgets, which stores the "\n" in
- >the array of chars which I have declared using a pointer.
- >
- >The thing is, I want to get rid of the "\n" and replace it with "\0", but
- >obviously I can only do this using the pointer. I'm using the following code:
- >
- >char *Contents < pointer to string
- >
- >int count = 0;
- >
- >
- >while (*(Contents + count)!= NULL) /* the end of string is not reached */
- >{if (*(Contents + count) == atoi("\n"))
- >/* change the \n to a \0 and set the next char along to null */
- >{
- >*(Contents + count) = atoi("\0");
- >
- >*(Contents + count + 1) = NULL;
- >
- >
- >}
- >else
- >/* read in the next char */
- >{
- >count++;
- >
- >I think the problem maybe my way of using the pointer - I can print out each
- >char as I get to it, but it doesnt seem to change the array at all.
- >Should I be using atoi?, it doesnt seem to work without it.
- >
- >Cheers
- >
- >ANdy
- >
-
- I don't know what you are trying to do with the function "atoi". What it
- does is convert an ascii string to an integer. The result of atoi("\n")
- will always be zero if I'm not mistaken because there are no digits in
- the string to be converted. Your "while" prior to the "if" assures
- you will never get to the "if" when you are pointing at a zero. Your "if"
- will never succeed while you are in the loop and you will never change the
- "\n" to a "\0".
-
- In any case, your program isn't doing anything you think it is. Here's a
- solution to removing the trailing '\n' from your string following a fgets().
-
- FILE *f;
- char s[255]; /* very large string for the read */
- int string_length;
-
- f = fopen ( ... ); /* open your file */
- /* ... do some error checking which I left out */
-
- fgets (s, 254, f);
- /* ... do some error checking which I left out */
-
- /* remove the '\n' if there is one at the end (there probably is) */
-
- string_length = strlen (s); /* use runtime library string routine */
- if (string_length > 0 && s[string_length-1] == '\n')
- s[string_length-1] = '\0'; /* notice the single quotes ('). You had
- double quotes (") in your example */
-
- .
- .
- .
-
- Hope this helps, Rick
-
-